/**
 * gitnote  local 保存图片的插件
 * 修改点： 保存文件路径修改，默认保存到 .assert 目录
 * 文件名命名： 时间全长 + @ + 文件原名（空格替换为_） + 原文件名后缀
 * 
 * 例：   .assert/20190709224800515@git_command.jpeg
 */
var fse = require('fs-extra')
var path = require('path')
var relative = require('relative')
const normalize = require('normalize-path')

Date.prototype.format = function(fmt) { 
  var o = { 
     "M+" : this.getMonth()+1,                 //月份 
     "d+" : this.getDate(),                    //日 
     "h+" : this.getHours(),                   //小时 
     "m+" : this.getMinutes(),                 //分 
     "s+" : this.getSeconds(),                 //秒 
     "q+" : Math.floor((this.getMonth()+3)/3), //季度 
     "S"  : this.getMilliseconds()             //毫秒 
 }; 
 if(/(y+)/.test(fmt)) {
         fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
 }
  for(var k in o) {
     if(new RegExp("("+ k +")").test(fmt)){
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
      }
  }
 return fmt; 
}       

var uploader = {
  upload: async function(files, option) {
    if (option && option.token) {
    }
    var d = new Date()
    var local = path.join(
      '.assert'
    )
    var fullpath = path.join(option.workpath, local)
    if (!fse.pathExistsSync(fullpath)) {
      fse.mkdirpSync(fullpath)
    }
    var results = []
    for (let i = 0; i < files.length; i++) {
      var f = files[i].path
      var filename = path.basename(f)
      var ext = path.extname(filename)
      var name = filename
        .split('.')
        .slice(0, -1)
        .join('.')
        .replace(/ /g,"_")
      var time = new Date().getTime() + ''
      var target = path.join(fullpath, new Date().format("yyyyMMddhhmmssS") + '@' + name + ext)
      fse.copyFileSync(f, target)
      var url = relative(option.editfile, target)
      url = normalize(url)
      try {
        results.push({
          code: 'ok',
          url: url,
          message: 'ok',
          file: files[i]
        })
      } catch (error) {
        results.push({
          code: 'warning',
          message: error.message,
          file: f
        })
      }
    }
    return results
  }
}

module.exports = uploader
